import React, {useRef, useState, useEffect} from 'react';
import {connect} from 'umi';
import {cloneDeep} from 'lodash';
import moment from 'moment';
import request from '@/utils/request'
import {ActionType, PageContainer, ProTable} from '@ant-design/pro-components';
import {Button, Upload, Modal, message, Form, DatePicker, Input, Table, Space, Popover} from 'antd';
import {CloudUploadOutlined, UploadOutlined, PlusOutlined} from '@ant-design/icons';
import {getSearchValues} from '@/utils';
import 'moment/locale/zh-cn';
moment.locale('zh-cn')

// let urlA = require("../../../public/icons/iconfont.svg");

const {TextArea} = Input;
const accessToken = sessionStorage.getItem('token');
const TableList: React.FC<unknown> = (props: any) => {
    // console.log('urlA', urlA)
    const {dispatch, dictData: {company = {}, client = {}, fileType = {}} = {}} = props;
    const [form] = Form.useForm();
    const [form2] = Form.useForm();
    const actionRef = useRef<ActionType>();
    const [fileStream, setFile]: any = useState([]);
    const [currentFile, setCurrentFile]: any = useState({});
    const [currentFileObj, setCurrentFileObj]: any = useState({});
    const [open, setOpen] = useState(false);
    const [openPile, setOpenPile] = useState(false);
    const [formModalOpen, setFormOpen] = useState(false);
    const [effectModalOpen, setEffectFormOpen] = useState(false);
    const [pileCode, setPileCode] = useState('');
    const [pileList, setPileList] = useState<any>([]);
    useEffect(() => {
        dispatch({
            type: 'files/init'
        })
    }, [dispatch]);
    const companyVals = getSearchValues(company);
    const clientVals = getSearchValues(client);
    const fileTypeVals = getSearchValues(fileType);
    const showModal = (obj: any) => {
        setCurrentFile(obj)
        setOpen(true);
    };

    const hideModal = () => {
        setOpen(false);
    };
    const showPileModal = () => {
        setOpenPile(true);
    };

    const hidePileModal = () => {
        setOpenPile(false);
    };
    const confirmAddPile = () => {
        if (pileCode && !pileList.includes(pileCode)) {
            setPileList([
                pileCode,
                ...pileList
            ]);
            message.success('添加成功');
            setPileCode('')
            setOpenPile(false);
        } else {
            message.warning('编号不能为空且不可重复输入')
        }
    }
    const confirmDel = () => {
        request(
            '/api1/new/file/deleteById',
            {
                method: 'get',
                params: {
                    id: currentFile.id
                }
            }
        ).then((response) => {
            if (response && response.code === 200) {
                message.success('删除成功');
                setOpen(false);
                if (actionRef.current) {
                    actionRef.current.reload();
                }
            } else {
                message.warning(response.msg)
            }
        })
    }
    const hideFileModal = () => {
        setFormOpen(false);
        form.resetFields();
        setFile([])
    }
    const submitFileForm = (values: any) => {
        console.log('pileList', pileList);
        console.log('values', values);
        const temForm = new FormData();
        // for (const d in values){
        //     temForm.append(d, values[d])
        // };
        temForm.append('file', fileStream[0])
        temForm.append('effectTime', values.effectTime2 ? moment(values.effectTime2).format('YYYY-MM-DD HH:mm:ss') : '');
        temForm.append('remark', values.remark || '');
        if (pileList.length) temForm.append('pileCodes', pileList);
        console.log('temForm', temForm);
        console.log('temForm', temForm.get('pileCodes'));
        // return;
        request(
            '/api1/new/file/upload',
            {
                method: 'POST',
                requestType: 'form',
                data: temForm,
            }
        ).then((response) => {
            if (response && response.code === 200) {
                message.success('上传成功');
                if (actionRef.current) {
                    actionRef.current.reload();
                    setFormOpen(false);
                    form.resetFields();
                    setFile([])
                }
            } else {
                message.warning(response?.msg)
            }
        })
    }
    const hideEffectModal = () => {
        setEffectFormOpen(false);
        form2.resetFields();
        setFile([])
    }
    const submitEffectForm = (values: any) => {
        console.log('values', values);
        console.log('pileList', pileList);
        request(
            '/api1/new/file/updateById',
            {
                method: 'get',
                params: {
                    id: values?.id,
                    pileCodes: pileList.length ? pileList.join(',') : ''
                }
            }
        ).then((response) => {
            // console.log('编辑生效范围', response);
            if(response.code && response.code === 200) {
                message.success('编辑成功');
                if (actionRef.current) {
                    actionRef.current.reload();
                    setEffectFormOpen(false);
                    form2.resetFields();
                    setFile([])
                }
            } else {
                message.warning(response?.msg || '编辑失败')
            }
        })
    }
    const range = (start, end) => {
        const result = [];
        for (let i = start; i < end; i++) {
            result.push(i);
        }
        return result;
    }
    const disabledTime = date => {
        const hour = moment().hours(); // 获取当前的小时
        const min = moment().minutes(); // 获取当前的分钟
        const second = moment().seconds(); // 获取当前秒
        if (date?.format('YYYY-MM-DD').valueOf() === moment().format('YYYY-MM-DD').valueOf()) {
            if (date?.format('HH').valueOf() === moment().format('HH').valueOf()) {
                if (date?.format('mm').valueOf() === moment().format('mm').valueOf()) {
                    return {
                        disabledHours: () => range(0, 24).splice(0, hour),
                        disabledMinutes: () => range(0, 60).splice(0, min),
                        disabledSeconds: () => range(0, 60).splice(0, second)
                    };
                } else {
                    return {
                        disabledHours: () => range(0, 24).splice(0, hour),
                        disabledMinutes: () => range(0, 60).splice(0, min)
                    };
                }
            } else {
                return {
                    disabledHours: () => range(0, 24).splice(0, hour)
                };
            }
        }
    };

    function size(bytes: any) {
        if (bytes >= 1073741824) {
            bytes = (bytes / 1073741824).toFixed(2) + " GB";
        } else if (bytes >= 1048576) {
            bytes = (bytes / 1048576).toFixed(2) + " MB";
        } else if (bytes >= 1024) {
            bytes = (bytes / 1024).toFixed(2) + " KB";
        } else if (bytes > 1) {
            bytes = bytes + " bytes";
        } else if (bytes === 1) {
            bytes = bytes + " byte";
        } else {
            bytes = "0 bytes";
        }
        return bytes;
    }
    async function downloadFile (obj: any){
        await fetch(`/api1/new/file/download?id=${obj.id}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
            },
        }).then(async (res) => {
            console.log('res', res);
            if (!res.ok) throw new Error(`HTTP错误! 状态码: ${res.status}`);
            if (!res.body) throw new Error('响应体为空'); // 新增检查
            if (res){
                const fileData: any = await res.blob(); // 或者用 response.arrayBuffer()
                console.log('fileData', fileData);
                const contentDisposition = res.headers.get('Content-Disposition');
                console.log('contentDisposition', contentDisposition);
                let filename = 'default_filename.ext'; // 默认文件名（如果解析失败）
                // 2. 解析 Content-Disposition 中的 filename
                if (contentDisposition) {
                    const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
                    if (filenameMatch && filenameMatch[1]) {
                        filename = filenameMatch[1].replace(/['"]/g, ''); // 去除引号
                    }
                }
                const blob = new Blob([fileData], { type: 'application/octet-stream' });
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = filename;
                link.click();
                URL.revokeObjectURL(url); // 释放内存
            }
        }).catch(error => {
            console.error('下载失败:', error);
            alert(`下载失败: ${error.message}`); // 用户友好提示
        });
    }
    const columns: any = [
        {
            title: '公司名称',
            dataIndex: 'company',
            // tip: '名称是唯一的 key',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '名称为必填项',
                    },
                ],
            },
            valueEnum: companyVals,
            render: (text, record) => {
                return (<span>{`${record.company_dict}[${record.company}]`}</span>)
            }
        },
        {
            title: '平台',
            dataIndex: 'clientType',
            // valueType: 'text',
            valueEnum: clientVals,
            render: (text, record) => {
                return (
                    <span>{`${record.clientType_dict}[${record.clientType}]`}</span>
                )
            }
        },
        {
            title: '版本号',
            dataIndex: 'version',
            valueType: 'text',
            search: false,
            render: (text, record) => {
                // console.log('record', record);
                return (
                    <div>
                        <span
                            style={{
                                display: 'inline-block',
                                height: '10px',
                                width: '10px',
                                borderRadius: '50%',
                                backgroundColor: record?.status ? 'green' : 'grey'
                            }}/>
                        <span style={{fontWeight: 'bold', color: record?.status ? 'green' : 'grey'}}> {text}</span>
                    </div>
                )
            }
        },
        {
            title: '文件类型',
            dataIndex: 'fileType',
            hideInForm: true,
            valueEnum: fileTypeVals,
            render: (text, record) => {
                return (
                    <span>{`${record.fileType_dict}[${record.fileType}]`}</span>
                )
            }
        },
        {
            title: '文件大小',
            dataIndex: 'size',
            search: false,
            render: (text, record) => {
                return (
                    <span>{size(text)}</span>
                )
            }
        },
        {
            title: '上传时间',
            dataIndex: 'createTime',
            search: false,
            render: (text, record) => {
                return (
                    <span>{moment(text).format('YYYY-MM-DD')}</span>
                )
            }
        },
        {
            title: '生效时间',
            dataIndex: 'effectTime',
            search: false,
            render: (text, record) => {
                return (
                    <span>{moment(text).format('YYYY-MM-DD HH:mm')}</span>
                )
            }
        },
        {
            title: '升级范围',
            dataIndex: 'pileCodes',
            search: false,
            render: (text, record) => {
                // console.log('pileCodes', record.pileCodes);
                return (
                    <span>{record.pileCodes ? <Popover
                        content={<div>{record.pileCodes.split(',').map((i) => i ? <div>桩号: {i}</div> : '')}</div>}
                        title="升级范围">
                        <a>部分生效</a>
                    </Popover> : <span>全部生效</span>}</span>
                )
            }
        },
        {
            title: '备注',
            dataIndex: 'remark',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'ope',
            search: false,
            render: (_, record) => {
                return <Space size='middle'>
                    <a onClick={() => {
                        setEffectFormOpen(true);
                        setCurrentFileObj(record);
                        setPileList(record?.pileCodes ? record?.pileCodes.split(',').map((i: any) => i).filter((l) => l) : [])
                        form2.setFieldsValue({...record})
                    }}>编辑</a>
                    <a onClick={() => downloadFile(record)}>下载</a>
                    <a onClick={() => showModal(record)} style={{color: 'red'}}>删除</a>
                </Space>
            }
        },
    ];
    const pileColumns: any = [
        {
            title: '序号',
            dataIndex: 'order',
            key: 'order',
            align: 'center'
        },
        {
            title: '桩编号',
            dataIndex: 'pileCode',
            key: 'pileCode',
            align: 'center'
        },
        {
            title: '操作',
            dataIndex: 'ope',
            key: 'ope',
            search: false,
            align: 'center',
            render: (_, record) => {
                return <a onClick={() => setPileList(pileList.filter((i: any) => i !== record.pileCode))}
                          style={{color: 'red'}}>删除</a>
            }
        },
    ]
    return (
        <PageContainer
            header={{
                title: '',
            }}
        >
            <ProTable<API.UserInfo>
                headerTitle="文件列表"
                actionRef={actionRef}
                pagination={{defaultPageSize: 10}}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    // <Upload
                    //     key="1"
                    //     maxCount={1}
                    //     action='/api1/new/file/upload'
                    //     showUploadList={false}
                    //     beforeUpload={(file, FileList) => {
                    //         console.log('file', file);
                    //         console.log('FileList', FileList);
                    //         const fileFamart = file.name.split('.')[file.name.split('.').length - 1];
                    //         if (fileFamart !== 'bin') {
                    //             message.warning('必须上传bin格式的文件!');
                    //             return false;
                    //         } else {
                    //             setFile([file])
                    //         }
                    //     }}
                    //     onChange={(info) => {
                    //         console.log('INFO', info);
                    //         const {file = {}} = info;
                    //         if (file?.status && file?.status === 'done') {
                    //             if (file.response && file.response.code === 200) {
                    //                 // confirm()
                    //                 message.success('上传成功');
                    //                 if (actionRef.current) {
                    //                     actionRef.current.reload();
                    //                 }
                    //             } else {
                    //                 message.warning(file.response?.msg)
                    //             }
                    //         }
                    //     }}
                    // >
                    //     <Button type="primary" icon={<CloudUploadOutlined/>}>
                    //         上传文件
                    //     </Button>
                    //     {contextHolder}
                    // </Upload>,
                    <Button
                        type="primary"
                        icon={<CloudUploadOutlined/>}
                        onClick={() => {
                            setFormOpen(true);
                            setPileList([]);
                            setPileCode('')
                        }}
                    >
                        新增升级文件
                    </Button>
                ]}
                request={async (params, sorter, filter) => {
                    // const { data, success } = await queryUserList({
                    //   ...params,
                    //   // FIXME: remove @ts-ignore
                    //   // @ts-ignore
                    //   sorter,
                    //   filter,
                    // });
                    // return {
                    //   data: data?.list || [],
                    //   success,
                    // };
                    const cloneParams = cloneDeep(params);
                    delete cloneParams.current;
                    const {data, code} = await request('/api1/new/file/pageList', {
                        params: {
                            ...cloneParams,
                            currentPage: params.current
                        }
                    });
                    if (code && code === 200) {
                        return {
                            data: data?.records || [],
                            success: true,
                            total: data?.total
                        };
                    }
                }}
                columns={columns}
            />
            <Modal
                title="新增升级文件"
                open={formModalOpen}
                width={680}
                onOk={form.submit}
                onCancel={hideFileModal}
                maskClosable={false}
                okText="确认"
                cancelText="取消"
            >
                <Form
                    labelCol={{span: 4}}
                    wrapperCol={{span: 14}}
                    layout="horizontal"
                    form={form}
                    style={{maxWidth: 600}}
                    onFinish={(values) => submitFileForm(values)}
                >
                    <Form.Item
                        label="升级文件"
                        name="file"
                        rules={[{required: true, message: '请上传升级文件'}]}
                    >
                        <Upload
                            action="/upload.do"
                            // listType="picture-card"
                            maxCount={1}
                            accept='bin'
                            fileList={fileStream}
                            beforeUpload={(file, FileList) => {
                                const fileFamart = file.name.split('.')[file.name.split('.').length - 1];
                                // setFile([file])
                                if (fileFamart !== 'bin') {
                                    message.warning('必须上传bin格式的文件!');
                                    return false;
                                } else {
                                    setFile([file])
                                }
                            }}
                        >
                            <Button icon={<UploadOutlined/>}>Click to Upload</Button>
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        name="effectTime2"
                        label="生效时间"
                        style={{display: 'none'}}
                    >
                    </Form.Item>
                    <Form.Item
                        name="effectTime"
                        label="生效时间"
                        rules={[{required: false, message: '请选择升级时间'}]}
                    >
                        <DatePicker
                            style={{width: '350px'}}
                            showTime
                            disabledDate={(current: any) => {
                                return current < moment().subtract(1, 'days').endOf('days');
                            }}
                            disabledTime={disabledTime}
                            onChange={(_, dateStr) => {
                                form.setFieldValue('effectTime2', moment(dateStr))
                            }}
                        />
                    </Form.Item>
                    <Form.Item
                        name="remark"
                        label="备注"
                        rules={[{required: false, message: ''}]}
                    >
                        <TextArea style={{width: '350px'}}/>
                    </Form.Item>
                    <Form.Item name="pileCodes" label="升级范围">
                        <Button onClick={() => showPileModal()} icon={<PlusOutlined/>} type='primary'
                                size='small'>添加充电桩</Button>
                    </Form.Item>
                    <Table
                        scroll={{y: 55 * 5}}
                        size='small'
                        dataSource={pileList && pileList.length ? pileList.map((i: string, index: number): any => {
                            return {order: index + 1, pileCode: i}
                        }) : []}
                        columns={pileColumns}
                        rowKey="pileCode"
                        style={{width: '500px', marginLeft: '90px'}}
                        pagination={{
                            showTotal: function () {
                                return `共${pileList.length}条`
                            }
                        }}
                    />
                </Form>
            </Modal>
            <Modal
                title="删除确认"
                open={open}
                onOk={confirmDel}
                onCancel={hideModal}
                okText="确认"
                cancelText="取消"
            >
                <p>是否确认要删除该文件?</p>
            </Modal>
            <Modal
                title="添加充电桩"
                open={openPile}
                onOk={confirmAddPile}
                onCancel={hidePileModal}
                okText="确认"
                cancelText="取消"
            >
                <br/>
                <Form.Item
                    name="piles"
                    label="桩编号"
                    rules={[{required: true, message: '输入桩编号',}]}
                > <Input placeholder='请输入桩编号' value={pileCode}
                         onChange={(e) => setPileCode(e.target.value)}/></Form.Item>
            </Modal>
            <Modal
                title="编辑生效范围"
                open={effectModalOpen}
                width={680}
                onOk={form2.submit}
                onCancel={hideEffectModal}
                maskClosable={false}
                okText="确认"
                cancelText="取消"
            >
                <Form
                    labelCol={{span: 4}}
                    wrapperCol={{span: 14}}
                    layout="horizontal"
                    form={form2}
                    style={{maxWidth: 600}}
                    onFinish={(values) => submitEffectForm(values)}
                >
                    <Form.Item
                        name="id"
                        label="生效时间"
                        style={{display: 'none'}}
                    >
                    </Form.Item>
                    <Form.Item
                        name="effectTime"
                        label="生效时间"
                        rules={[{required: false, message: '请选择升级时间'}]}
                    >
                        <span>{form2.getFieldValue('effectTime')}</span>
                    </Form.Item>
                    <Form.Item name="pileCodes" label="升级范围">
                        <Button onClick={() => showPileModal()} icon={<PlusOutlined/>} type='primary'
                                size='small'>添加充电桩</Button>
                    </Form.Item>
                    <Table
                        scroll={{y: 55 * 5}}
                        size='small'
                        dataSource={pileList && pileList.length ? pileList.map((i: string, index: number): any => {
                            return {order: index + 1, pileCode: i}
                        }) : []}
                        columns={pileColumns}
                        rowKey="pileCode"
                        style={{width: '500px', marginLeft: '90px'}}
                        pagination={{
                            showTotal: function () {
                                return `共${pileList.length}条`
                            }
                        }}
                    />
                </Form>
            </Modal>
        </PageContainer>
    );
};

export default connect(({files}) => {
    return {...files}
})(TableList);
